<script setup>
import {getProject,deleteMember,addMember,updateProjectStatus,deleteProject,updateProject,uploadProjectFile,deleteProjectFile,joinProject} from '@/api/project.js';
import {getStudentInfo} from '@/api/student.js';
import { QuillEditor } from "@vueup/vue-quill"; // 引入富文本编辑器组件
import "@vueup/vue-quill/dist/vue-quill.snow.css"; // 引入默认样式
import { useRoute } from 'vue-router';
import { useRouter } from "vue-router"; // 导入 useRouter

import { ref } from "vue";
import {ElMessage, ElAvatar, ElTag, ElMessageBox} from "element-plus";
import { useUserStore } from '@/stores/user'
const userStore = useUserStore()


const route = useRoute();
const router = useRouter(); // 使用 useRouter

const project_data = ref({});
const  student_data = ref([]);
const projectId = route.query.productId;
const  student_display = ref(false)
const  delete_display = ref(false)

const user_id = userStore.userDetails.userId;
console.log(user_id);
const password = ref("");

const  total = ref(0)
const filters = ref({
   userName:null,
   className:null,
   academy:null,

  pageNum:1,
  pageSize:5
})
const editDialogVisible = ref(false); // 弹窗可见性
const isEditDisabled = ref(true); // 是否禁用编辑
const editForm = ref({
  id: null,
  projectName: "",
  startTime: "",
  endTime: "",
  image: "",
  lab: "",
  description: "",
});

// 回显项目信息
const handleEditProject = () => {
  isEditDisabled.value = true; // 默认禁用编辑
  editForm.value = {
    id: project_data.value.id,
    projectName: project_data.value.projectName,
    startTime: project_data.value.startTime, // 假设这里是服务器返回的日期
    endTime: project_data.value.endTime,
    image: project_data.value.image,
    lab: project_data.value.lab,
    description: project_data.value.description,
  };
  editDialogVisible.value = true;
};

// 允许编辑
const enableEdit = () => {
  isEditDisabled.value = false;
};
// 工具函数：格式化时间为本地日期字符串
const formatDateToLocal = (date) => {
  const d = new Date(date);
  return `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, '0')}-${d.getDate().toString().padStart(2, '0')}`;
};
// 保存修改
const saveProjectChanges = async () => {
  // 格式化时间为本地日期格式（例如：YYYY-MM-DD）
  editForm.value.startTime = formatDateToLocal(editForm.value.startTime);
  editForm.value.endTime = formatDateToLocal(editForm.value.endTime);

  const updatedData = {};
  for (const key in editForm.value) {
    if (editForm.value[key] !== project_data.value[key] && editForm.value[key]) {
      updatedData[key] = editForm.value[key];
    }
  }

  if (Object.keys(updatedData).length === 0) {
    ElMessage.warning("请至少修改一项内容后再保存！");
    return;
  }

  ElMessageBox.confirm("确认保存修改吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
      .then(async () => {
        const response = await updateProject({ id: project_data.value.id, ...updatedData });
        if (response.data.code === 200) {
          ElMessage.success("项目修改成功！");
          await fetchProject(); // 重新获取项目数据
          editDialogVisible.value = false; // 关闭弹窗
        } else {
          ElMessage.error(response.data.msg);
        }
      })
      .catch(() => {
        ElMessage.info("已取消保存修改");
      });
};



const fetchProject = async () => {
  const response = await getProject(projectId);
  if (response.data.code === 200) {
    project_data.value = response.data.data;

  } else {
    ElMessage.error(response.data.msg);
  }
};

// 获取学生信息,根据 filters
const fetchStudents = async () => {
  student_display.value = true;
  console.log(student_display.value)
  const response = await getStudentInfo(filters.value);
  if (response.data.code === 200) {
    student_data.value = response.data.data.rows;
    console.log(student_data.value)
    total.value = response.data.data.total;
    console.log("总数"+total.value)
  }
  else {
    ElMessage.error(response.data.msg);
  }

  };


// 删除成员
const handleDeleteMember = async (projectId, userId) => {
  // 显示确认对话框
  ElMessageBox.confirm('此操作将删除该成员，是否继续？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    // 用户点击了确定按钮
    const response = await deleteMember(projectId, userId);
    if (response.data.code === 200) {
      ElMessage.success('删除成功');
      // 假设fetchProject是一个异步函数，用于重新获取项目数据
      await fetchProject();
    } else {
      ElMessage.error(response.data.msg);
    }
  }).catch(() => {
    // 用户点击了取消按钮或关闭了对话框
    ElMessage.info('已取消删除');
  });
};
// 添加成员
const handleAddMember = async (project_id, user_id) => {
  // 使用 ElMessageBox 进行确认
  ElMessageBox.confirm('您确定要添加该成员吗？', '确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
      .then(async () => {
        const response = await addMember(project_id, user_id);
        if (response.data.code === 200) {
          ElMessage.success('添加成功');
          await fetchProject(); // 刷新项目数据
          student_display.value = false; // 关闭学生信息弹窗
        } else {
          ElMessage.error(response.data.msg);
        }
      })
      .catch(() => {
        // 用户点击了取消
        ElMessage.info('已取消添加成员');
      });
};

// 修改项目状态
const handleStopProject = async (projectId, status) => {
  // 根据状态确定提示信息
  const action = status === -1 ? '停止' : '启动';
  const message = `您确定要${action}该项目吗？`;

  // 使用 ElMessageBox 进行确认
  ElMessageBox.confirm(message, '确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
      .then(async () => {
        const response = await updateProjectStatus(projectId, status);
        if (response.data.code === 200) {
          ElMessage.success(`项目已${action}`);
          await fetchProject(); // 刷新项目数据
        } else {
          ElMessage.error(response.data.msg);
        }
      })
      .catch(() => {
        // 用户点击了取消
        ElMessage.info(`已取消${action}项目`);
      });
};

// 删除项目的逻辑
const handleDeleteProject = (projectId) => {
  delete_display.value = true; // 打开删除确认弹窗
};

// 确认删除
const confirmDeleteProject = async (projectId) => {
  if (!password.value) {
    ElMessage.error("请输入密码进行验证！");
    return;
  }
  // 显示确认对话框
  ElMessageBox.confirm('此操作将永久删除该项目，是否继续？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    console.log("用户信息"+userStore.userDetails.value)
    const response = await deleteProject(projectId, user_id, password.value);
    if (response.data.code === 200) {
      ElMessage.success('项目删除成功');
      delete_display.value = false; // 关闭弹窗
      // 可在此处添加重新加载项目列表的逻辑
      await router.push("/home/view-projects");
    } else {
      ElMessage.error(response.data.msg);
    }
  })
};
//重置学生表单
const resetFilters = async () => {
  filters.value = {
    userName:null,
    className:null,
    academy:null,
    pageNum:1,
    pageSize:5

}
await fetchStudents(filters.value)
}
const handlePageChange = (page) => {
  filters.value.pageNum = page; // 更新当前页
  fetchStudents(); // 重新获取数据
};

const handleSizeChange = (size) => {
  filters.value.pageSize = size; // 更新每页显示数量
  fetchStudents(); // 重新获取数据
};

// 图片上传成功回调
const handleUploadSuccess = async (file) => {
  const formData = new FormData();
  formData.append("image", file.raw); // 获取图片文件
  formData.append("projectId", editForm.value.id); // 添加项目 ID

  try {
    const response = await uploadProjectFile(formData);
    if (response.data.code === 200) {
      editForm.value.image = response.data.data; // 更新图片 URL
      ElMessage.success("图片上传成功！");
    } else {
      ElMessage.error(response.data.msg || "图片上传失败！");
    }
  } catch (error) {
    ElMessage.error("图片上传过程中发生错误！");
    console.error(error);
  }
};
// 删除图片
const handleDeleteImage = async (url) => {
  ElMessageBox.confirm("确认删除当前图片吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
      .then(async () => {
        try {
          const response = await deleteProjectFile(url);
          if (response.data.code === 200) {
            editForm.value.image = ""; // 清空图片 URL
            ElMessage.success("图片删除成功！");
          } else {
            ElMessage.error(response.data.msg || "图片删除失败！");
          }
        } catch (error) {
          ElMessage.error("图片删除过程中发生错误！");
          console.error(error);
        }
      })
      .catch(() => {
        ElMessage.info("已取消删除图片");
      });
};

// 加入项目
const handleJoinProject = async (projectId) => {
  // 显示确认框
  ElMessageBox.confirm('您确定要加入这个项目吗？', '确认加入项目', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
      .then(async () => {
        // 用户点击了确认
        const response = await joinProject(projectId, user_id);
        if (response.data.code === 200) {
          ElMessage.success("加入申请已提交，请等待审核！");
          await fetchProject(); // 刷新项目数据
        } else {
          ElMessage.error(response.data.msg);
        }
      })
      .catch(() => {
        // 用户点击了取消
        ElMessage.info('您已取消加入项目');
      });
};


fetchProject();
</script>

<template>
  <div class="project-detail-container">
    <!-- 项目详情 -->
    <section class="project-section">
      <h1 class="section-title">项目详情</h1>
      <div class="project-info">
        <h2>{{ project_data.projectName }}</h2>
        <img :src="project_data.image" alt="项目图片" class="project-image" />
        <!-- 使用v-html来渲染description中的HTML标签 -->
     <div style="margin-top: 20px;"> 项目描述：  <p class="project-description" v-html="project_data.description"></p> </div>
        项目状态：  <ElTag :type="project_data.status === 1 ? 'success' : 'info'">
         {{ project_data.status === 1 ? '进行中' : '已停止' }}
        </ElTag>
<!--        项目基地-->
        <p>项目基地：{{ project_data.lab }}</p>
<!--        项目开展时间-->
        <p>项目开展时间：{{ new Date(project_data.startTime).toLocaleDateString() }} - {{ new Date(project_data.endTime).toLocaleDateString() }}</p>
        <!--      修改项目信息、停止项目、删除项目按钮-->
        <div v-if="userStore.userInfo === 'teacher'" class="project-actions">
          <el-button  type="success" @click="handleEditProject">修改项目信息</el-button>
<!--          status为1时显示停止项目按钮，status为-1时显示启动项目按钮-->
          <el-button  v-if="project_data.status === 1" type="danger" @click="handleStopProject(projectId, -1)">停止项目</el-button>
          <el-button  v-if="project_data.status === -1" type="success" @click="handleStopProject(projectId, 1)">启动项目</el-button>

          <el-button style="margin-left:  30px;" type="danger" @click="handleDeleteProject(projectId)">删除项目</el-button>
        </div>
      </div>
      <!-- 项目删除确认弹窗 -->
      <el-dialog
          v-model="delete_display"
          title="删除项目"
          width="400px"
      >
        <p>请输入密码以确认删除该项目：</p>
        <el-input
            v-model="password"
            type="password"
            placeholder="请输入密码"
            show-password
            clearable
         ></el-input>
        <template #footer>
          <el-button @click="delete_display = false; password = ''" >取消</el-button>
          <el-button type="primary" @click="confirmDeleteProject(projectId)">确认删除</el-button>
        </template>
      </el-dialog>

      <!-- 修改项目信息弹窗 -->
      <el-dialog
          v-model="editDialogVisible"
          title="修改项目信息"
          width="70%"
      >
        <el-form :model="editForm" label-width="100px">
          <el-form-item label="项目名称">
            <el-input
                v-model="editForm.projectName"
                :disabled="isEditDisabled"
                placeholder="请输入项目名称"
            ></el-input>
          </el-form-item>

          <el-form-item label="项目时间">
            <el-date-picker
                v-model="editForm.startTime"
                type="date"
                :disabled="isEditDisabled"
                placeholder="请选择开始时间"
            />
            至
            <el-date-picker
                v-model="editForm.endTime"
                type="date"
                :disabled="isEditDisabled"
                placeholder="请选择结束时间"
            />
          </el-form-item>

          <el-form-item label="项目基地">
            <el-input
                v-model="editForm.lab"
                :disabled="isEditDisabled"
                placeholder="请输入项目基地"
            ></el-input>
          </el-form-item>

          <el-form-item label="项目图片">
            <div>
              <img
                  style="width: 300px; height: 200px; margin-left: 10px"
                  :src="editForm.image"
                  alt="项目图片"
                  class="project-image"
              />
              <el-upload
                  :on-change="handleUploadSuccess"
                  :show-file-list="false"
                  accept="image/*"
              >
                <el-button size="small" type="primary" :disabled="isEditDisabled">
                  选择图片
                </el-button>
              </el-upload>
              <el-button
                  size="small"
                  type="danger"
                  :disabled="!editForm.image || isEditDisabled"
                  @click="handleDeleteImage(editForm.image)"
              >
                删除
              </el-button>
            </div>
          </el-form-item>


          <el-form-item label="项目描述">
            <textarea
                v-model="editForm.description"
                style="height: 300px; width: 100%;overflow-y: auto; "
                :readonly="isEditDisabled"
            ></textarea>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button v-if="isEditDisabled" type="primary" @click="enableEdit">修改</el-button>
          <el-button v-else type="success" @click="saveProjectChanges">保存</el-button>
          <el-button @click="editDialogVisible = false">取消</el-button>
        </template>
      </el-dialog>






    </section>

    <!-- 指导老师 -->
    <section class="teacher-section">
      <h1 class="section-title">指导老师信息</h1>
      <div class="teacher-info">
        <img :src="project_data.teacher.avatar || 'https://via.placeholder.com/100'" alt="老师头像" class="teacher-avatar" />
        <div class="teacher-details" style="margin-left: 25px;">
          <h2>{{ project_data.teacher.name }} - {{ project_data.teacher.professional }}</h2>
          <p>研究方向：{{ project_data.teacher.major }}</p>
          <p>{{ project_data.teacher.description }}</p>
        </div>
      </div>
    </section>

    <!-- 学生信息 -->
    <section class="students-section">
      <h1 class="section-title">项目成员信息</h1>
      <div class="students-list">
        <div
            class="student-card"
            v-for="(user, index) in project_data.users"
            :key="user.userId"
        >
          <img :src="user.avatar || 'https://via.placeholder.com/80'" alt="学生头像" class="student-avatar" />
          <div class="student-details">
            <h3>
              {{ user.userName }}
              <span v-if="index === 0" class="leader-tag">（项目负责人）</span>
            </h3>
            <p>邮箱：{{ user.email }}</p>
            <p>电话：{{ user.phone }}</p>
            <p>学院：{{ user.academy }}</p>
            <p>班级：{{ user.className }}</p>
            <p>{{ user.description }}</p>
          </div>
          <div v-if="index !== 0 && (userStore.userInfo === 'teacher' || (project_data.users.length > 0 && project_data.users[0].userName === userStore.userDetails.userName))" class="student-actions">
            <el-button type="danger" @click="handleDeleteMember(projectId, user.userId)">删除成员</el-button>
          </div>

        </div>
      </div>
<!--      添加成员按钮 ||project_data.users.userName ===userStore.userDetails.userName -->
      <div v-if="userStore.userInfo === 'teacher' || (project_data.users.length > 0 && project_data.users[0].userName === userStore.userDetails.userName)" class="add-student-btn">
        <el-button style="width: 200px" type="primary" @click="fetchStudents()"> 添加成员 </el-button>
      </div>
      <div v-else class="add-student-btn">
        <el-button style="width: 200px" type="primary" @click="handleJoinProject(projectId) ">加入项目 </el-button>
      </div>

    </section>
    <!-- 分页查询学生信息和条件查询 -->
 <el-dialog v-model="student_display" title="查询学生信息" width="70%" style="height: 550px;">
    <el-form :inline="true" :model="filters" style="margin-left: 60px;">
      <el-form-item label="姓名">
        <el-input v-model="filters.userName" style="width: 140px;"></el-input>
      </el-form-item>
      <el-form-item label="班级">
        <el-input v-model="filters.className" style="width: 140px;"></el-input>
      </el-form-item>
      <el-form-item label="学院">
        <el-input v-model="filters.academy" style="width: 150px;"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchStudents">查询</el-button>
<!--        重置-->
        <el-button type="success" @click="resetFilters">重置</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="student_data" style="width: 100%">
      <el-table-column label="头像" width="80">
        <template #default="{ row }">
          <el-avatar :size="40" :src="row.avatar || 'https://via.placeholder.com/80'"></el-avatar>
        </template>
      </el-table-column>
      <el-table-column prop="userName" label="姓名" width="100"></el-table-column>
      <el-table-column prop="email" label="邮箱" width="150"></el-table-column>
      <el-table-column prop="phone" label="电话"></el-table-column>
      <el-table-column prop="academy" label="学院"></el-table-column>
      <el-table-column prop="className" label="班级"></el-table-column>
      <el-table-column label="操作" width="100">
        <template #default="{ row }">
          <el-button type="success" @click="handleAddMember(projectId, row.userId)">添加</el-button>
        </template>
      </el-table-column>


      </el-table>
<!--      分页参数-->
   <el-pagination
       background
       layout="total, prev, pager, next"
       :current-page="filters.pageNum"
       :page-sizes="[5, 10, 15, 20]"
       :page-size="filters.pageSize"
       :total="total"
       @current-change="handlePageChange"
       @size-change="handleSizeChange"
        style="margin-top: 20px;margin-left:300px;"
   />



 </el-dialog>
  </div>
</template>


<style scoped>
.project-detail-container {
  padding: 20px;
  width: 1000px;
  margin: 0 auto;
  font-family: Arial, sans-serif;
}

.section-title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 20px;
  color: #333;
  border-bottom: 2px solid #409EFF;
  padding-bottom: 5px;
  text-align: center;
}

.project-section, .teacher-section, .students-section {
  margin-bottom: 40px;
}

.project-info {
  background: #f9f9f9;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.project-info h2 {
  font-size: 22px;
  color: #409EFF;
  text-align: center;
}

.project-description {
  font-size: 16px;
  margin: 10px 0;
  color: #555;
}

.project-image {
  margin-top: 10px;
  width: 800px;
  height: 400px;
  border-radius: 8px;
  display: block;
  margin-left: auto;
  margin-right: auto;
}

.teacher-info {
  display: flex;
  align-items: center;
  background: #fffaf0;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.teacher-avatar {
  width: 100px;
}

.teacher-details h2 {
  margin: 0;
  font-size: 20px;
  color: #333;
}

.teacher-details p {
  margin: 5px 0;
  font-size: 14px;
  color: #555;
}

.students-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.student-card {
  display: flex;
  align-items: flex-start;
  background: #f0f9ff;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  width: 100%;
}

.student-avatar {
  margin-right: 15px;
  width: 150px;

}

.student-details h3 {
  margin: 0;
  font-size: 18px;
  color: #409EFF;
}

.student-details p {
  margin: 5px 0;
  font-size: 14px;
  color: #666;
}

.leader-tag {
  color: #e91e63;
  font-size: 14px;
}
.student-actions {
  margin-top: 60px;
  margin-left:700px;
  position: absolute;
}
.add-student-btn{
  margin-top: 20px;
  margin-left:40%;
}
.project-actions{
  display: flex;
  margin-left: 30%;
  padding: 10px;

}
</style>
